#include "useradd.h"
#include "ui_useradd.h"
#include "commonfunction.h"
#include <QMessageBox>
#include <QApplication>
#include <QDesktopWidget>
#include "msgbox.h"
#include "authmanager.h"
#include "frminput2019.h"
#include "userlogger.h"

UserAdd::UserAdd(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UserAdd)
{
    ui->setupUi(this);
    bdf = BllDataFlow::getInstance();
    sqlHelper = SqlHelper::getInstance();

    //Signals and Slots
    connect(bdf, &BllDataFlow::showAllRolesSignal,this,&UserAdd::showAllRolesSlot);
    connect(bdf, &BllDataFlow::retranslateUiSignal, this, &UserAdd::retranslateUiSlot);

    initWidget();
}

UserAdd::~UserAdd()
{
    delete ui;
}

void UserAdd::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    QPainter painter(this);
    painter.fillRect(this->rect(), QColor(255, 255, 255, 0));
}

void UserAdd::on_btnClose_clicked()
{
    this->hide();
}

void UserAdd::retranslateUiSlot()
{
    ui->retranslateUi(this);
}

void UserAdd::on_btnConfirmAddUser_clicked()
{
    frmInput2019::Instance()->hideAndClearFocus();

    Role role;
    user.name = ui->lineUsername->text().trimmed();
    user.role = ui->cbxRole->currentText();
    role.name = user.role;
    user.permission = sqlHelper->selectRolePermission(role);
    user.status = ui->btnIsOn->isChecked();
    user.createDatetime = currentDateTime();
    user.remark = ui->lineRemark->text().trimmed();
    user.password = USER_INIT_PASSWORD;
    user.failLoginTimes = 0;

    if (!checkUserName())
    {
        ui->lineUsername->selectAll();
        ui->lineUsername->setFocus();
        return;
    }

    if (!checkRoleName())
    {
        return;
    }

    EttaError ret = sqlHelper->insertUser(user);
    if (ret == EttaError::OK)
    {
        UserLogger::log(QString("%1: %2, %3: %4").arg(tr("Add User")).arg(user.name).arg(tr("Role is")).arg(user.role));
        bdf->showAllUsers(true);
        this->hide();
    }
    else
    {
        UserLogger::error(QString(tr("Failed to Add User %1")).arg(user.name));
        QString result = (ret == EttaError::OK) ? tr("Success") : tr("Failed");
        MsgBox::information(this, tr("Add User"), QString(tr("%1 to Add User")).arg(result));
    }
}

void UserAdd::on_btnCancelAddUser_clicked()
{
    this->hide();
}

void UserAdd::initWidget()
{
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect();
    shadow->setColor(QColor(0,0,0,150));
    shadow->setOffset(1, 1);
    shadow->setBlurRadius(16);
    ui->widget_8->setGraphicsEffect(shadow);
    setAttribute(Qt::WA_TranslucentBackground, true);
    setWindowFlags(windowFlags() | Qt::SubWindow);
    ui->cbxRole->setView(new QListView());
    ui->cbxRole->view()->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    this->location = this->geometry();
    ui->lineUsername->setValidator(gUsernameValidator);
    ui->lineUsername->setPlaceholderText(tr("1~15 letters or numbers"));
    ui->lineRemark->setPlaceholderText(tr("optional"));
    showAllRolesSlot();
    clearInput();
}

bool UserAdd::checkUserName()
{
    user.name = ui->lineUsername->text().trimmed();

    if (user.name.isEmpty())
    {
        MsgBox::information(this, tr("User"), tr("Username cannot be empty!"));
        return false;
    }

    if (AuthManager::instance()->isPresetAccount(user.name))
    {
        MsgBox::information(this, tr("User"), tr("Username is not allowed!"));
        return false;
    }

    if (sqlHelper->checkUserExist(user.name))
    {
        MsgBox::information(this, tr("User"), tr("This user already exists!"));
        return false;
    }

    return true;
}

bool UserAdd::checkPassWord()
{
    if (user.password.length() < MIN_PASSWORD_LENGTH)
    {
        MsgBox::information(this, tr("User"), QString(tr("Password less than %1 !")).arg(MIN_PASSWORD_LENGTH));
        return false;
    }

    if (user.password != confirmPW)
    {
        MsgBox::information(this, tr("User"), QString(tr("Confirming password error!")));
        return false;
    }

    //check password contain uppercase, lowercase and digit
    bool pwValid = checkPwValid(user.password);
    if (!pwValid)
    {
        MsgBox::information(this, tr("User"), tr("Password should contain uppercase, lowercase and digit!"));
        return false;
    }

    return true;
}

bool UserAdd::checkRoleName()
{
    if (ui->cbxRole->currentText().isEmpty())
    {
        MsgBox::information(this, tr("User"), tr("The role list is empty, please create it first"));
        return false;
    }

    return true;
}

void UserAdd::clearInput()
{
    ui->lineUsername->clear();
    ui->lineRemark->clear();
    ui->btnIsOn->setChecked(true);
    if (ui->cbxRole->count() > 0)
    {
        ui->cbxRole->setCurrentIndex(0);
    }
}

void UserAdd::on_btnIsOn_toggled(bool checked)
{
    if(checked)
    {
        user.status  = 1;
        ui->btnIsOn->setText(tr("On"));
    }
    else
    {
        user.status = 0;
        ui->btnIsOn->setText(tr("Off"));
    }
}

void UserAdd::showAllRolesSlot()
{
    ui->cbxRole->clear();

    QList<Role> info = sqlHelper->selectAllRoles();
    for (int r = 0; r < info.size(); r++)
    {
        if (!AuthManager::instance()->isManufacturer(info[r].name) &&
            !AuthManager::instance()->isAdministrator(info[r].name))
        {
            ui->cbxRole->addItem(info[r].name);
        }
    }
}

void UserAdd::on_btnMenu_Close_clicked()
{
    close();
}

void UserAdd::on_lineUsername_returnPressed()
{
    if (!checkUserName())
    {
        ui->lineUsername->selectAll();
        ui->lineUsername->setFocus();
    }
}
